import { Alert } from 'antd'
import { useEffect, useState } from 'react'

import { handleInsuranceApi } from '@/api/pcs/insurance'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import AekUpload from '@/components/AekUpload'
import { requestWithTry } from '@/utils/request'

const HandleModal = ({ row = {}, view = false }) => {
  const [form] = AekForm.useForm()
  const [detail, setDetail] = useState({})
  const { id } = row

  useEffect(() => {
    if (!row.id) return
    if (view) {
      setDetail({
        ...row,
        appendix: row.appendix ? JSON.parse(row.appendix) : [],
      })
    }
    form.setFieldsValue({
      ...row,
      appendix: row.appendix ? JSON.parse(row.appendix) : [],
    })
  }, [row.id])

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      field: 'handlingRemark',
      label: '办理备注',
      component: { name: 'Input' },
    },
    {
      field: 'appendix',
      label: '附件',
      formItemProps: {
        help: '支持扩展名：.png .jpg .doc .pdf',
      },
      component: {
        name: 'AekUpload',
        props: { fileType: 'unset' },
      },
      viewRender: value => {
        return value?.length > 0 ? (
          <AekUpload
            limitFileNum={value?.length ?? 0}
            value={value}
            showUploadList={{
              showRemoveIcon: false,
            }}
          />
        ) : (
          '-'
        )
      },
    },
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    const params = {
      id,
      ...values,
      appendix: values.appendix?.map(({ url, name }) => ({ url, name })),
    }
    await requestWithTry(handleInsuranceApi, params)
  }
  return (
    <AekModal title={view ? '查看' : '办理'} width={500} onOk={onOk} showFooter={!view}>
      <Alert
        message={view ? '已办理长护险业务。' : '已办理长护险业务？'}
        type={view ? 'success' : 'warning'}
        showIcon
        className='mb-4'
      />
      <AekForm allView={view} form={form} detail={detail} formData={formData} />
    </AekModal>
  )
}

HandleModal.PromiseThen = PromiseThen

export default HandleModal
